<template>
  <common-layout>
    <div class="top">
      <div class="header">
        <img alt="logo" class="logo" src="@/assets/img/login/loginLogo.png" />
        <!-- <span class="title">陇县奶山羊大数据平台</span> -->
      </div>
      <!-- <div class="desc">Ant Design 是西湖区最具影响力的 Web 设计规范</div> -->
    </div>
    <div class="login">
      <h3>欢迎登录!</h3>
      <a-form-model
        @submit="onSubmit"
        :model="form"
        ref="loginFormRef"
        :rules="rules"
      >
        <a-alert
          type="error"
          :closable="true"
          v-show="error"
          :message="error"
          showIcon
          style="margin-bottom: 24px"
        />
        <!-- 用户名 -->
        <a-form-model-item prop="loginName">
          <a-input
            autocomplete="autocomplete"
            size="large"
            placeholder="请输入用户名"
            v-model="form.loginName"
          >
            <a-icon slot="prefix" type="user" style="color:#579C27"/>
          </a-input>
        </a-form-model-item>
        <!-- 密码 -->
        <a-form-model-item prop="password">
          <a-input
            size="large"
            placeholder="请输入用户密码"
            autocomplete="autocomplete"
            type="password"
            v-model="form.password"
          >
            <a-icon slot="prefix" type="lock" style="color:#579C27"/>
          </a-input>
        </a-form-model-item>
        <!-- 验证码 -->
        <a-form-model-item class="loginYZMimg" prop="captcha">
          <a-input
            class="loginYZMimg111"
            size="large"
            placeholder="请输入右侧验证码"
            v-model="form.captcha"
          >
            <a-icon slot="prefix" type="unlock"  style="color:#579C27"/>
          </a-input>
          <!-- <img
            src=""
            alt=""
          /> -->
          <img
            class="loginYZMimg"
            :src="loginYZM.imgBase64Str"
            alt=""
            @click="updateYZM"
            title="换一张"
          />
        </a-form-model-item>
        <!-- <a-tab-pane tab="手机号登录" key="2">
            <a-form-item>
              <a-input size="large" placeholder="mobile number" >
                <a-icon slot="prefix" type="mobile" />
              </a-input>
            </a-form-item>
            <a-form-item>
              <a-row :gutter="8" style="margin: 0 -4px">
                <a-col :span="16">
                  <a-input size="large" placeholder="captcha">
                    <a-icon slot="prefix" type="mail" />
                  </a-input>
                </a-col>
                <a-col :span="8" style="padding-left: 4px">
                  <a-button style="width: 100%" class="captcha-button" size="large">获取验证码</a-button>
                </a-col>
              </a-row>
            </a-form-item>
          </a-tab-pane> -->
        <!-- 立即注册  忘记密码 -->
        <div class="registerAndpassword">
          <span @click="toRegister">立即注册</span>
          <span @click="forgetPassword" style="float: right;color: #579C27;">忘记密码?</span>
        </div>
        <!-- 用户登录按钮 -->
        <a-form-item>
          <a-button
            :loading="logging"
            style="
              width: 360px;
              height: 52px;
              background: #579C27;
              border-radius: 6px;
              margin-top: 24px;
              border: none;
            "
            size="large"
            @click="onSubmit"
            type="primary"
            >登录
          </a-button>
        </a-form-item>
      </a-form-model>
    </div>
  </common-layout>
</template>

<script>
import CommonLayout from "@/layouts/CommonLayout";
import { login, getLoginYZM } from "@/services/user";
import { setAuthorization } from "@/utils/request";
import { loadRoutes } from "@/utils/routerUtil";
import { mapMutations } from "vuex";
import { getRoutesConfig, queryUserTenantList } from "../../services/user";
import { AUTH_TYPE } from "../../utils/request";

export default {
  name: "Login",
  components: { CommonLayout },
  data() {
    return {
      rules: {
        loginName: [
          {
            required: true,
            message: "请输入用户名",
            whitespace: true,
            trigger: "blur",
          },
        ],
        password: [
          {
            required: true,
            message: "请输入用户密码",
            whitespace: true,
            trigger: "blur",
          },
        ],
        captcha: [
          {
            required: true,
            message: "请输入验证码",
            whitespace: true,
            trigger: "blur",
          },
        ],
      },
      logging: false,
      error: "",
      // form: this.$form.createForm(this),
      form: {
        loginName: "",
        password: "",
        callChannel: "3",
        mobileType: "111",
        captcha: "",
        codeImgId: "",
      },
      loginYZM: {},
    };
  },
  created() {
    this.updateYZM();
  },
  computed: {
    systemName() {
      return this.$store.state.setting.systemName;
    },
    menuData() {
      return this.$store.state.setting.menuData;
    },
  },
  methods: {
    ...mapMutations("account", ["setUser", "setPermissions", "setRoles"]),
    // 用户注册
    toRegister() {
      this.$router.push({ path: "/register"});

      //  this.$router.push({name: '注册页'})
    },
    // 忘记密码
    forgetPassword(){
      this.$router.push({ path: "/forgetPassword"})
    },
    // 刷新验证码
    updateYZM() {
      getLoginYZM().then((res) => {
        this.loginYZM = res.data.data;
        this.form.codeImgId = res.data.data.codeImgId;
        this.form.captcha = "";
      });
    },
    // 用户点击登录
    onSubmit(e) {
      e.preventDefault();
      this.$refs.loginFormRef.validate((valid) => {
        if (valid) {
          this.logging = true;
          // const name = this.form.getFieldValue("name");
          // const password = this.form.getFieldValue("password");
          // 登录之前对密码进行加密
          let params = {
            ...this.form
          }
          params.tenantCode = "T000010";
          login(params).then(this.afterLogin).catch(err => {console.log(err);this.logging = false;this.updateYZM();});
        } else {
          this.logging = false;
          return false;
        }
      });
    },
    afterLogin(res) {
      this.logging = false;
      const loginRes = res.data;
      if (loginRes.status == 0) {
        const loginResAll = loginRes.data;
        this.setUser(loginResAll);
        this.setRoles(loginResAll.userType);
        sessionStorage.setItem("roleType", loginResAll.userType); //重点在这里
        setAuthorization(
          {
            token: loginResAll.token,
            expireAt: new Date(loginResAll.expireAt),
          },
          AUTH_TYPE.BASIC
        );
        if (loginResAll.userType == "PLATFORM_ADMIN") {// 超级管理员
          //超级管理员配置菜单
          // this.$router.push("/dashboard/workplace");
          // this.$message.success(loginRes.message, 3);


           sessionStorage.setItem(
                "tenantCode",
                ""
              );
          sessionStorage.setItem(
              "subjectInfoId",
              ""
          );
          sessionStorage.setItem(
              "subjectEnterpriseType",
              ""
          );
          sessionStorage.setItem(
              "milkStationFlag",
              ""
          );
          getRoutesConfig({
            channelTypeTmp: "PC",
            tenantCode:"",
          }).then((result) => {

            const routesConfig = result.data.data;
            let router = [
              {
                resKey: "root",
                children: routesConfig.rows,
              },
            ];
            console.log(router)
            loadRoutes(router);
            console.log(this.getFirstPath(this.menuData[0]).fullPath)
            this.$router.push(this.getFirstPath(this.menuData[0]).fullPath);
            // this.$message.success(loginRes.message, 3);
          });
        } else {
          //注册用户需要逻辑判断
          console.log(loginResAll,'查看登录返回数据')
          if (loginResAll.tenantInfoAuditStatus == "WAIT_INPUT") {
            //  this.$router.push({name: '注册页'})

            // this.$router.push({
            //   path: "register",
            //   query: { loginUserId: loginResAll.loginUserId, current: 1 },
            // });
          } else {
            queryUserTenantList({}).then((userTenantList) => {
              console.log(userTenantList);
              let val = userTenantList.data.data.rows[0]
              let catalogue = val.roleCode == 'expert' ? 2 : (val.roleCode == 'farmersMilkStation' || val.roleCode == 'farmers') ? 1 : 0
              let enterpriseRegisterTypeCode = ''
              if (val.roleCode =="breedEnterpriseMilkStation" || val.roleCode == "breedEnterprise") {
                  enterpriseRegisterTypeCode = "BREED_ENTERPRISE";
                } else if (val.roleCode == "machinEnterprise") {
                  enterpriseRegisterTypeCode = "PROCESSING_ENTERPRISE";
                }
              let milkStationFlag = ''
              if (
                  val.roleCode ==
                    "breedEnterpriseMilkStation" ||
                  val.roleCode == "machinEnterprise" ||
                  val.roleCode == "farmersMilkStation"
                ) {
                  milkStationFlag = 0;
                } else if (
                  val.roleCode == "breedEnterprise" ||
                  val.roleCode == "farmers"
                ) {
                  milkStationFlag = 1;
                }
              if(val.auditStatus == 99){
                  this.$router.push({
                    path: "register",
                    query: { loginUserId: loginResAll.loginUserId, current: 1,catalogue,enterpriseRegisterTypeCode,milkStationFlag},
                  });
              }else if(val.auditStatus == 0){
                  this.$router.push({
                    path: "register",
                    query: { loginUserId: loginResAll.loginUserId, current: 2},
                  });
              }else if(val.auditStatus == 2){
                  this.$router.push({
                    path: "register",
                    query: { loginUserId: loginResAll.loginUserId,current: 1,catalogue,reviewResults:true},
                  });
              }else if(val.auditStatus == 1){
                sessionStorage.setItem(
                "tenantCode",
                userTenantList.data.data.rows[0].tenantCode || ''
              );
              sessionStorage.setItem(
                "subjectInfoId",
                userTenantList.data.data.rows[0].subjectInfoId || ''
              );
              sessionStorage.setItem(
                "subjectEnterpriseType",
                userTenantList.data.data.rows[0].subjectEnterpriseType || ''
              );
              sessionStorage.setItem(
                "milkStationFlag",
                userTenantList.data.data.rows[0].milkStationFlag || ''
              );
              //重点在这里
              getRoutesConfig({
                channelTypeTmp: "PC",
                tenantCode: userTenantList.data.data.rows[0].tenantCode || '',
              }).then((result) => {
                const routesConfig = result.data.data;
                // 无权限跳转登录页
                if(routesConfig.rows.length == 0){
                  this.$message.error('暂无权限,请联系管理员');
                  this.$router.push('/login');
                  return
                }
                let router = [
                  {
                    resKey: "root",
                    children: routesConfig.rows,
                  },
                ];
                loadRoutes(router);
                this.$router.push(this.getFirstPath(this.menuData[0]).fullPath);
                // this.$message.success(loginRes.message, 3);
              });
              }

            });
          }
        }
      } else {
        this.updateYZM();
      }
      // if (loginRes.status == 0) {
      //
      //   const loginResAll = loginRes.data;
      //
      //   if (loginResAll.userType == 'PLATFORM_ADMIN') {//超级管理员配置菜单
      //     this.$router.push("/dashboard/workplace");
      //
      //     //调菜单列表接口
      //   } else {//调租户列表
      //
      //
      //   }
      //
      //
      // } else {
      //   this.error = loginRes.msg;
      //   getLoginYZM().then((res) => {
      //     this.loginYZM = res.data.data;
      //     this.form.codeImgId = res.data.data.codeImgId;
      //     this.form.captcha = ''
      //   });
      // }
      // 登录成功
      // if (loginRes.status !== 101105 && loginRes.status !== 210010 && loginRes.status !== 210002) {
      //   // // const { user, permissions, roles } = loginRes.data;
      //   // // this.setUser(user);
      //   // // this.setPermissions(permissions);
      //   // // this.setRoles(roles);
      //   // setAuthorization({
      //   //   token: loginRes.data.token,
      //   //   // expireAt: new Date(loginRes.data.expireAt),
      //   // });
      //   // // 获取路由配置
      //   // // getRoutesConfig().then((result) => {
      //   // //   const routesConfig = result.data.data;
      //   // //   loadRoutes(routesConfig);
      //   // this.$router.push("/dashboard/workplace");
      //   // // this.$message.success(loginRes.message, 3);
      //   // // });
      //   // // 登录失败
      // } else {
      //   this.error = loginRes.msg;
      //   getLoginYZM().then((res) => {
      //     this.loginYZM = res.data.data;
      //     this.form.codeImgId = res.data.data.codeImgId;
      //     this.form.captcha = ''
      //   });
      // }
    },
    getFirstPath(router) {
      console.log(router,'全部')
      if(router){
        if (router.children && router.children.length > 0) {
        return this.getFirstPath(router.children[0]);
      } else {
        return router;
      }
      }else{
        this.$message.error('暂无权限请联系管理员')
        localStorage.clear()
        sessionStorage.clear()
      }

    },
  },
};
</script>

<style lang="less" scoped>

  .top {
    position: fixed;
    top: 40px;
    left: 40px;
    /* text-align: center; */

    .header {
      height: 44px;
      line-height: 44px;

      a {
        text-decoration: none;
      }

      .logo {
        vertical-align: top;
        margin-right: 20px;
        width: 405px;
        height: 72px;
      }

      .title {
        font-size: 32px;
        color: #333;

        position: relative;
        top: 16px;
      }
    }

    .desc {
      font-size: 14px;
      color: @text-color-second;
      margin-top: 12px;
      margin-bottom: 40px;
    }
  }

  .login {
    h3 {
      width: 120px;
      height: 30px;
      font-size: 24px;
      font-family: PingFangSC-Medium, PingFang SC;
      font-weight: 500;
      color: #579C27;
      line-height: 30px;
      margin-bottom: 30px;
    }

    width: 360px;
    margin: 0 auto;
    @media screen and (max-width: 576px) {
      width: 95%;
    }
    @media screen and (max-width: 320px) {
      .captcha-button {
        font-size: 14px;
      }
    }

    .icon {
      font-size: 24px;
      color: @text-color-second;
      margin-left: 16px;
      vertical-align: middle;
      cursor: pointer;
      transition: color 0.3s;

      &:hover {
        color: @primary-color;
      }
    }

    .loginYZMimg {
      white-space: nowrap;
      .loginYZMimg111 {
        width: 285px;
        height: 52px;
        line-height: 52px;
      }

      img {
        width: 90px;
        height: 30px;
        cursor: pointer;
      }
    }

    .registerAndpassword span {
      width: 64px;
      height: 22px;
      font-size: 16px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #333333;
      line-height: 22px;
      cursor: pointer;

      &:hover {
        color: #00afaf;
      }
    }

    .registerAndpassword span:nth-child(2) {
      width: 80px;
      color: #579c27;
    }
  }

</style>
